//
//  ClassificationOfDiseaseController.m
//  KMedicine
//
//  Created by 余伟康 on 16/7/8.
//  Copyright © 2016年 caomu. All rights reserved.
//

#import "ClassificationOfDiseaseController.h"
#import "Utils.h"
#import "UserDTO.h"
#import "NSString+pinyin.h"
#import "UIView+Frame.h"
#import "AkuNetWorkTool.h"


///屏幕宽高
#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)

@interface ClassificationOfDiseaseController ()<UITableViewDataSource,UITableViewDelegate>

// 存储模型的数组
@property (nonatomic,strong)NSMutableArray *storeUserDTOList;

// 搜索组
@property (nonatomic,strong) NSMutableArray *seachUserDTOList;

// 是否在搜索状态
@property (nonatomic, assign) BOOL isSearchState;

// 用textFiled 来当搜索框使用
@property (nonatomic,weak) UITextField *searchBar;

// teableView
@property (nonatomic,weak) UITableView *tableView;

@end

@implementation ClassificationOfDiseaseController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 界面搭建
    [self setupUI];

    // 数据更新
    [self loadDataWithButtonNumber:self.ClickButtonNumer +1];
    
}


#pragma mark
#pragma mark - 界面搭建

- (void)setupUI{
    
    // 去除导航栏的偏移量
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.edgesForExtendedLayout = UIRectEdgeBottom | UIRectEdgeLeft | UIRectEdgeRight;

    UIButton * leftBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    [leftBtn setImage:[UIImage imageNamed:@"JianTou"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    
    UITableView *tableView = [[UITableView alloc]init];
    self.tableView = tableView;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    
    UITextField *searchBar = [[UITextField alloc]init];
    searchBar.frame = CGRectMake(0, 0, 200, 30);
    searchBar.backgroundColor = [UIColor whiteColor];
    searchBar.placeholder = @"请输入关键字";
    searchBar.clearButtonMode = UITextFieldViewModeWhileEditing;
    searchBar.borderStyle = UITextBorderStyleRoundedRect;
    self.navigationItem.titleView = searchBar;
    
    // 添加约束
    [self setViewMasonry];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange:) name:UITextFieldTextDidChangeNotification object:nil];
}

#pragma mark -
#pragma mark - 返回上一个控制器
- (void)goBack{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark
#pragma mark - 添加约束

- (void)setViewMasonry{
    
    // tableView
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.offset(0);
    }];

}

#pragma mark
#pragma mark - 数据更新

// 假数据
- (void)loadData2{

    NSArray *nameArr = @[@"中国",@"上海",@"浦江",@"三鲁公路",@"传智播客",@"屌炸天",@"训练营",@"iOS2期",@"PanJinLian",@"三鲁公路1239号"];
    for (int i = 0; i < nameArr.count; ++i) {
        UserDTO *dto = [[UserDTO alloc] init];
        //转拼音
        NSString *PinYin =  [nameArr[i] transformToPinyin];
        //首字母
        NSString *FirstLetter = [nameArr[i] transformToPinyinFirstLetter];
        
        dto.name = nameArr[i];
        dto.namePinYin = PinYin;
        dto.nameFirstLetter = FirstLetter;
        
        [self.storeUserDTOList addObject:dto];
    }
    
    [self.tableView reloadData];
}

- (void)loadDataWithButtonNumber:(int)number{

    //2.疾病细分接口
    //    请求地址: http://iosapi.itcast.cn/searchCI3List.json.php
    //    请求参数:{"page":1,"page_size":15,"ci1_id":1,"keyword":""}
    
    /*
     肿瘤     ci1_id = 1
     心血管   ci1_id = 2
     神经科   ci1_id = 3
     血液科   ci1_id = 4
     骨科     ci1_id = 5
     公益活动 ci1_id = 6
     */
    NSDictionary * dic1 = nil;
    switch (number) {
        case 1:
            dic1 = @{@"page":@1,@"page_size":@15,@"ci1_id":@1,@"keyword":@""};
            break;
            
        case 2:
            dic1 = @{@"page":@1,@"page_size":@15,@"ci1_id":@2,@"keyword":@""};
            break;
            
        case 3:
            dic1 = @{@"page":@1,@"page_size":@15,@"ci1_id":@3,@"keyword":@""};
            break;
            
        case 4:
            dic1 = @{@"page":@1,@"page_size":@15,@"ci1_id":@4,@"keyword":@""};
            break;
            
        case 5:
            dic1 = @{@"page":@1,@"page_size":@15,@"ci1_id":@5,@"keyword":@""};
            break;
            
        default:
            break;
    }
    
    [AkuNetWorkTool POST_RequestWithURLString:@"http://iosapi.itcast.cn/searchCI3List.json.php" params:dic1 successBlock:^(id responseObject) {
        
        NSArray * array = responseObject[@"data"];
        
        [array enumerateObjectsUsingBlock:^(NSDictionary *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString * str = obj[@"ci3_name"];
//            NSLog(@"%@",str);
            
            UserDTO *dto = [[UserDTO alloc]init];
            
            //转拼音
            NSString *PinYin =  [str transformToPinyin];
            //首字母
            NSString *FirstLetter = [str transformToPinyinFirstLetter];
            dto.name = str;
            dto.namePinYin = PinYin;
            dto.nameFirstLetter = FirstLetter;

            [self.storeUserDTOList addObject:dto];
        }];
        
        [self.tableView reloadData];
        
    } errorBlock:^(NSError *error) {
        NSLog(@"error");
        
    }];
    
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    //如果想自定义更多，就把noResultLab 换成一个大的BJView，里面再填充很多个小的控件
    UILabel *noResultLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
    
    noResultLab.font = [UIFont systemFontOfSize:20];
    noResultLab.textColor = [UIColor lightGrayColor];
    noResultLab.textAlignment = NSTextAlignmentCenter;
    noResultLab.hidden = YES;
    noResultLab.text = @"抱歉！没有搜索到相关数据";
    tableView.backgroundView = noResultLab;
    
    
    if (_isSearchState) {
        
        if (self.seachUserDTOList.count > 0) {
            
            noResultLab.hidden = YES;
            
            return self.seachUserDTOList.count;
            
        }else{
            
            noResultLab.hidden = NO;
            
            return 0;
        }
    }else{
        
        return self.storeUserDTOList.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    UserDTO *dto = nil;
    
    if (_isSearchState) {
        
        dto = self.seachUserDTOList[indexPath.row];
    }else{
        
        dto = self.storeUserDTOList[indexPath.row];
    }
    
    cell.textLabel.text = dto.name;
    
    return cell;
}

/** 监听 */
- (void)textChange:(NSNotification *)note{
    
    UITextField *textField = (UITextField *)[note object];
    
    //如果项目大，搜索的地方多，就要使用多线程，然后在刷新tableview的时候，回到主线程
    [self startSearch:textField.text];
}


//开始搜索
-(void)startSearch:(NSString *)string{
    
    if (self.seachUserDTOList.count>0) {
        
        [self.seachUserDTOList removeAllObjects];
    }
    
    //开始搜索
    NSString *key = string.lowercaseString;
    NSMutableArray *tempArr = [NSMutableArray array];
    
    // NSLog(@"key = %@",key);
    
    if (![key isEqualToString:@""] && ![key isEqual:[NSNull null]] && key != nil) {
        
        [self.storeUserDTOList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            UserDTO *dto = self.storeUserDTOList[idx];
            
            //担心框架有时候会误转，再次都设置转为小写
            NSString *name = dto.name.lowercaseString;
            NSString *namePinyin = dto.namePinYin.lowercaseString;
            NSString *nameFireLetter = dto.nameFirstLetter.lowercaseString;
            
            NSRange rang1 = [name rangeOfString:key];
            if (rang1.length>0) { ///比牛 -比
                
                [tempArr addObject:dto];
            }else{
                
                if ([nameFireLetter containsString:key]) { //bn - b
                    
                    [tempArr addObject:dto];
                    
                }else{  //ershou
                    
                    if ([nameFireLetter containsString:[key substringToIndex:1]]) {
                        
                        if ([namePinyin containsString:key] ) {
                            [tempArr addObject:dto];
                        }
                    }
                }
            }
        }];
        
        [tempArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if (![self.seachUserDTOList containsObject:tempArr[idx]]) {
                
                [self.seachUserDTOList addObject:tempArr[idx]];
            }
        }];
        
        //NSLog(@"self.searchResultList  = %@",self.seachUserDTOList);
        self.isSearchState = YES;
    }else{
        
        self.isSearchState = NO;
    }
    
    [self.tableView reloadData];
}

#pragma mark
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    UserDTO *Dto =self.storeUserDTOList[indexPath.row];
//    NSLog(@"点击了%@",Dto.name);
    if (self.dtoBlock) {
        
        self.dtoBlock(Dto.name);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
    
    
}


#pragma mark  - Lazy
- (NSMutableArray *)storeUserDTOList{
    if (_storeUserDTOList == nil) {
        _storeUserDTOList = [[NSMutableArray alloc] init];
    }
    return _storeUserDTOList;
}

- (NSMutableArray *)seachUserDTOList{
    if (_seachUserDTOList == nil) {
        _seachUserDTOList = [[NSMutableArray alloc] init];
    }
    return _seachUserDTOList;
}

@end














